<?php
/**
 * Devin Ellis Sample Code
 * Example Model from 3do3dont.com
 * This is production code, no changes have been made for this portfolio.
 * 9/17/2011
 */
class DDD_Movies extends DDD_Model
{
	/**
	 * Class definition
	 */
	protected $_class = __CLASS__;

	/**
	 * The primary key for the table
	 *
	 * @var mixed
	 */
	protected $_primary = 'movieID';

	/**
	 * Resource names
	 *
	 * @var string
	 */
	const RES_CACHE 			= 'DDD_Cache_File';
	const RES_DATABASE 			= 'DDD_Database';
	const RES_CLASS_DATABASE 	= 'db1';
	const RES_CONF_TABLES 		= 'tables';
	const RES_TABLE 			= 'movies';

	/**
	 * Cache prefix
	 *
	 * @var string
	 */
	protected $_cachePrefix = 'DDD_Movies';
	const CACHE_LIFETIME = 30;

	/**
	 * Constructor
	 *
	 * @return void
	 */
	public function  __construct()
	{
		$this->_table = self::RES_TABLE;
		$this->setCache(DDD_Registry::get(self::RES_CACHE));
		$this->setCacheLifetime(self::CACHE_LIFETIME);
		parent::__construct(DDD_Registry::get(self::RES_DATABASE)->getConnection(self::RES_CLASS_DATABASE));

		// This initializes our data (fields) array
		$this->_data = array(
			'movieID'			=> 0,
			'imdbID'			=> NULL,
			'tmdbID'			=> NULL,
			'rottenTomatoesID'	=> NULL,
			'fandangoID'		=> NULL,
			'name'				=> NULL,
			'shortName'			=> NULL,
			'urlSegment'		=> NULL,
			'verdict'			=> NULL,
			'runtime'			=> NULL,
			'posterID'			=> NULL,
			'bannerID'			=> NULL,
			'rating'			=> NULL,
			'tsReleased'		=> NULL,
			'tsCreated'			=> date('Y-m-d H:i:s'),
			'tsUpdated'			=> date('Y-m-d H:i:s'),
			'tsRemoved'			=> '0000-00-00 00:00:00',
			'status'			=> 'enabled',
		);

		// Set field logic methods
		$this->_validators = array(
			'movieID'			=> 'DDD_Filter::integer',
			'imdbID'			=> 'DDD_Filter::integer',
			'tmdbID'			=> 'DDD_Filter::integer',
			'rottenTomatoesID'	=> 'DDD_Filter::integer',
			'fandangoID'		=> 'DDD_Filter::integer',
			'name'				=> 'DDD_Filter::plaintext',
			'shortName'			=> 'DDD_Filter::plaintext',
			'urlSegment'		=> true,
			'verdict'			=> 'DDD_Filter::int',
			'runtime'			=> 'DDD_Filter::time',
			'posterID'			=> 'DDD_Filter::integer',
			'bannerID'			=> 'DDD_Filter::integer',
			'rating'			=> 'DDD_Filter::plaintext',
			'tsReleased'		=> 'DDD_Filter::date',
			'tsCreated'			=> 'DDD_Filter::datetime',
			'tsUpdated'			=> 'DDD_Filter::datetime',
			'tsRemoved'			=> 'DDD_Filter::datetime',
			'status'			=> 'DDD_Filter::plaintext',
		);
	}

	/**
	 * Magic set method for urlSegment. Must be unique
	 * @param string $urlName
	 * @return void
	 */
	protected function _setUrlSegment($url)
	{
		if($this->whereEqual('urlSegment', $url)->returnOne()) {
			throw new Exception('URL already exists');
		}
		$this->_data['urlSegment'] = DDD_Filter::slug($url);
	}
	
    /**
     * fetches current movies
     */
    public function fetchCurrent()
    {
		$this->setTableAlias('m')
			->join('images', 'i.imageID = m.posterID', 'i')
			->whereEqual('tsRemoved', '0000-00-00')
			->OrderByDesc('tsReleased')
			->fetchMany();
	}
	
    /**
     * Returns the movietime link for this movie
     */
    public function movieTimes()
    {
		return 'http://www.fandango.com/3do3dont_' . $this->fandangoID . '/movietimes/';
    }
	
	/**
	 * Returns the CJ link for this movie
	 * @param link text
	 * @return string
	 */
	public function fandangoLink($text = 'Buy tickets at fandango.com')
	{
		if(!$this->fandangoID) return false;
		
		return '
		<a class="button" href="http://www.kqzyfj.com/click-5447514-10504407?url=' . urlencode($this->movieTimes()) . '">
			<img src="/img/fandango_16.png">
			' . $text . '
		</a>
		<img src="http://www.ftjcfx.com/image-5447514-10504407" width="1" height="1" border="0"/>';
	}
	
	/**
	 * Calculates the movie's verdict
	 * @return int $totalScore;
	 */
	public function calculateVerdict()
	{
		$totalScore = 0;
		$totalWeight = 0;
		
		// Make sure a movie is selected
		if($this->movieID == 0) {
			return;
		}
		
		// Lookup criteria
		$criteria = new DDD_MovieCriterias();
		$criterias = $criteria->getByMovie($this->movieID);
		$totalCriteria = count($criterias);
		
		// Calculate criteria scores, taking weight into account
		foreach($criterias as $criteria) {
			$totalScore += $criteria->score * $criteria->weight;
			$totalWeight += $criteria->weight;
		}
		
		// Divide weighted score by total weight
		$verdict = $totalScore / $totalWeight;
		
		// Get reviews
		$reviews = new DDD_Reviews();
		$reviews->getByMovie($this->movieID);
		$totalScore = 0;
		$totalWeight = 0;
		foreach($reviews->collection() as $review) {
			if($review->score > 0) {
				$totalScore += $review->verdict * $review->score;
				$totalWeight += $review->score;
			}
		}
		
		// combine criteria verdict and review verdict
		$verdict = $verdict + ($totalScore / $totalWeight) / 2;
		$verdict = round($verdict);
		
		
		$this->_data['verdict'] = $verdict;
		$this->forceAllDirty()->save();
		
		return $verdict;
	}
}
